package com.tg.app.activity.device;

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.appbase.custom.constant.DeviceStateConstants;
import com.demo.view.TimeRuleView;
import com.tange.base.toolkit.DateUtil;
import com.tange.base.toolkit.DimenUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.core.device.facade.ConnectStatus;
import com.tange.core.device.facade.Status;
import com.tange.core.media.render.DeviceMediaRender;
import com.tange.core.media.render.DeviceScreenRecord;
import com.tange.core.media.source.impl.local.DeviceStorageMediaSource;
import com.tange.core.media.source.impl.local.DeviceStoragePlayback;
import com.tange.core.universal.instructions.StorageInstruction;
import com.tg.app.R;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.CameraHelper;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.util.LocalThumbnailUtils;
import com.tg.app.view.MsgCenterToast;
import com.tg.app.widget.ZoomView;
import com.tg.appcommon.android.Packet;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.data.http.entity.WheelData;
import com.tg.message.adapter.MessageDateAdapter;
import com.tg.message.adapter.MessagePlaybackAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class CameraPipPlaybackActivity extends PlaybackActivity {
    private FrameLayout playerContainer, playerContainerPiP;
    private View viewContainer;
    private RelativeLayout recordTimeLayout;
    private TextView recordTimeText;

    private int playerHeight = 0;
    private LinearLayout linearLayout;
    protected DeviceMediaRender deviceMediaRenderPiP;
    private int selectDayIndex = 0;
    private long firstTime = 0;


    public void createDeviceMediaRender() {
        deviceMediaSource = new DeviceStorageMediaSource(deviceFacade);
        deviceMediaRender = new DeviceMediaRender(this, deviceMediaSource);
        deviceMediaRenderPiP = new DeviceMediaRender(this, deviceMediaSource);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pip_playback);
        hideActionBar();
        if (DeviceHelper.is4GDevice(mDevice) && !DeviceHelper.is4GExpired(mDevice, true)) {
            if (mDevice.isOnline()) {
                deviceFacade.connect();
            }
        }

        initView();
        initData();
    }

    private void switchFullScreen() {
        setRequestedOrientation(isLandscape? ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        findViewById(R.id.setting).setVisibility(isLandscape? View.VISIBLE : View.GONE);
        xBanner.setVisibility(isLandscape? View.VISIBLE : View.GONE);
        viewContainer.setVisibility(isLandscape? View.VISIBLE : View.GONE);
        setCameraViewHeight(isLandscape? playerHeight : LinearLayout.LayoutParams.MATCH_PARENT);
        isLandscape = !isLandscape;

        if (isLandscape){
            playerContainer.setVisibility(currentPlayer == 0? View.VISIBLE : View.GONE);
            playerContainerPiP.setVisibility(currentPlayer == 0? View.GONE : View.VISIBLE);
            if (currentPlayer == 0){
                playerContainer.post(() -> deviceMediaRender.resize());
            }else{
                playerContainerPiP.post(() -> deviceMediaRenderPiP.resize());
            }
        }else{
            playerContainer.setVisibility(View.VISIBLE);
            playerContainerPiP.setVisibility(View.VISIBLE);
            selectedLayout();
        }
    }

    public void screenSaveLocal() {
        Bitmap bmp = deviceMediaRender.screenshot();
        if (bmp == null) {
            return;
        }
        if (mDevice != null) {
            int pixel = bmp.getPixel(0,0);
            int pixel20 = bmp.getPixel(20,20);
            if (pixel==pixel20&&pixel==0){
                return;
            }
            LocalThumbnailUtils.getInstance().saveLocalThumbnail(bmp, mDevice.uuid);
        }
    }

    @Override
    protected Bitmap getSaveBitmap() {
        return currentPlayer == 0? deviceMediaRender.screenshot() : deviceMediaRenderPiP.screenshot();
    }


    public void screenSaveEnd() {
        TGLog.d(TAG, "click screenSaveEnd");
        recordTimeLayout.setVisibility(View.GONE);
    }

    public void recordingUpdate(long duration) {
        int time = (int) (duration / 1000);
        String timeStr = DateUtil.formatTimeHHmmss(time);
        timeStr = timeStr.substring(3);
        recordTimeText.setText(timeStr);
        if (recordTimeLayout.getVisibility() == View.GONE) {
            TGLog.d(TAG, "click recordingUpdate");
            TGLog.trace(TAG);
            recordTimeLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void recordStart() {
        if (currentPlayer == 0){
            if (!deviceMediaRender.screenRecord().isStarted()) {
                deviceMediaRender.screenRecord().start();
                TGToast.showToast(R.string.start_screen_record);
            }
        }else{
            if (!deviceMediaRenderPiP.screenRecord().isStarted()) {
                deviceMediaRenderPiP.screenRecord().start();
                TGToast.showToast(R.string.start_screen_record);
            }
        }
    }



    private void showBanner(){
        List<String> list = new ArrayList<>();
        list.add(ResourcesUtil.getString(R.string.fullscreen));
        list.add(ResourcesUtil.getString(R.string.speed));
        list.add(ResourcesUtil.getString(R.string.event_sound));
        list.add(ResourcesUtil.getString(R.string.record_screen));
        list.add(ResourcesUtil.getString(R.string.screen_shot));

        deviceFunHelper.setParam(list);
        deviceFunHelper.setListener((view, title) -> {
            if (canClickDeviceFun()){
                TGLog.i(TAG, "onBannerClick: " + title);

                if (!StringUtils.isEmpty(title)){

                    if (StringUtils.equalsIgnoreCase(title, ResourcesUtil.getString(R.string.fullscreen))) {
                        switchFullScreen();
                    }else if (StringUtils.equalsIgnoreCase(title, ResourcesUtil.getString(R.string.speed))) {
                        speedClick();
                    }else if (StringUtils.equalsIgnoreCase(title, ResourcesUtil.getString(R.string.event_sound))) {
                        if (view instanceof ImageView) {
                            switchAudio((ImageView) view);
                        }
                    }else if (StringUtils.equalsIgnoreCase(title, ResourcesUtil.getString(R.string.record_screen))) {
                        screenCapClick();
                    }else if (StringUtils.equalsIgnoreCase(title, ResourcesUtil.getString(R.string.screen_shot))) {
                        screenShotResult();
                    }
                }
            }else{
                showErrorTip();
            }

        });

        TGThreadPool.executeOnUiThread(() -> {
            deviceFunHelper.refreshTools();
            deviceFunHelper.initBanner(CameraPipPlaybackActivity.this);
            deviceFunHelper.showBanner(true);
        });

    }

    private void initData(){
        deviceMediaRender.setVideoFrameFilter(mediaFrame -> mediaFrame != null && mediaFrame.getData().getSubType() == 0);
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        layoutParams.gravity = Gravity.CENTER;
        deviceMediaRender.attach(playerContainer, layoutParams);


        deviceMediaRender.observeFirstFrameRendered(() -> {
            TGLog.i(TAG, "[first-rendered] ");
            rendered = true;
            loadingView.setVisibility(View.GONE);
        });

        deviceMediaRender.screenRecord().setRecordStatusObserver(new DeviceScreenRecord.RecordStatusObserver() {
            @Override
            public void onStart() {
                TGLog.i(TAG, "[RecordStatusObserver][onStart] ");
                isSaving = true;
                recordingUpdate(0);
            }

            @Override
            public void onDurationUpdate(long duration) {
                TGLog.i(TAG, "[RecordStatusObserver][onDurationUpdate] ");
                if (isSaving) {
                    runOnUiThread(() -> recordingUpdate(duration));
                }
            }

            @Override
            public void onComplete(boolean success) {
                TGLog.i(TAG, "[RecordStatusObserver][RecordStatusObserver] " + success);
                isSaving = false;
                runOnUiThread(() -> screenSaveEnd());
            }
        });


        deviceMediaRenderPiP.setVideoFrameFilter(mediaFrame -> mediaFrame != null && mediaFrame.getData().getSubType() == 1);
        FrameLayout.LayoutParams layoutParams1 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        layoutParams1.gravity = Gravity.CENTER;
        deviceMediaRenderPiP.attach(playerContainerPiP, layoutParams1);


        deviceMediaRenderPiP.observeFirstFrameRendered(() -> {
            TGLog.i(TAG, "[first-rendered] ");
            rendered = true;
            loadingView.setVisibility(View.GONE);
        });

        deviceMediaRenderPiP.screenRecord().setRecordStatusObserver(new DeviceScreenRecord.RecordStatusObserver() {
            @Override
            public void onStart() {
                TGLog.i(TAG, "[RecordStatusObserver][onStart] ");
                isSaving = true;
                recordingUpdate(0);
            }

            @Override
            public void onDurationUpdate(long duration) {
                TGLog.i(TAG, "[RecordStatusObserver][onDurationUpdate] ");
                if (isSaving) {
                    runOnUiThread(() -> recordingUpdate(duration));
                }
            }

            @Override
            public void onComplete(boolean success) {
                TGLog.i(TAG, "[RecordStatusObserver][RecordStatusObserver] " + success);
                isSaving = false;
                runOnUiThread(() -> screenSaveEnd());
            }
        });
        deviceMediaRender.setOnTimestampUpdate(aLong -> {

        });

        ((DeviceStorageMediaSource)deviceMediaSource).observeOnNextPartStarted(aLong -> {
            TGLog.i(TAG, "[observeOnNextPartStarted] " + aLong + ", time = " + DateUtil.formatTimeHHmmss(mPlayBackFragment.getSecondDay(aLong)));
            if (mPlayBackFragment != null){
                mPlayBackFragment.onPlaybackSDNextTimePart(aLong);
            }
        });
    }


    private void switchAudio(ImageView audio) {
        if (deviceMediaSource.isAudioProduceEnabled()) {
            audio.setImageResource(R.drawable.ic_tange_live_soundoff);
            deviceMediaSource.enableAudioProduce(false);
            deviceMediaRender.enableAudioRender(false);
            deviceMediaRenderPiP.enableAudioRender(false);
        } else {
            audio.setImageResource(R.drawable.ic_tange_live_soundon);
            deviceMediaSource.enableAudioProduce(true);
            deviceMediaRender.enableAudioRender(true);
            deviceMediaRenderPiP.enableAudioRender(true);
        }
    }


    private void setCameraViewHeight(int height) {
        LinearLayout.LayoutParams cameraViewLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
        linearLayout.setLayoutParams(cameraViewLayoutParams);
    }

    @Override
    protected void initView() {
        super.initView();
        int h = getResources().getDisplayMetrics().widthPixels;
        playerHeight = h * 9 / 8 + DimenUtil.dp2px(this, 2);
        linearLayout = findViewById(R.id.linearlayout);
        xBanner = findViewById(R.id.banner);
        deviceFunHelper.setBanner(xBanner);
        playerContainer = findViewById(R.id.player_container);
        playerContainerPiP = findViewById(R.id.player_container_pip);
        loadingView = findViewById(R.id.loading);
        loadingView.setVisibility(View.VISIBLE);
        connectView = findViewById(R.id.connect);

        connectView.setOnClickListener(v -> {
            if (StringUtils.equalsIgnoreCase(connectView.getText().toString(), getString(R.string.playback_none_sdcard_video))){
                return;
            }
            if (StringUtils.equalsIgnoreCase(connectView.getText().toString(), getString(R.string.no_video_please_to_scroll))){
                return;
            }
            if (StringUtils.equalsIgnoreCase(connectView.getText().toString(), getString(R.string.sim_service_expired))){
                return;
            }

            if (StringUtils.equalsIgnoreCase(connectView.getText().toString(), getString(R.string.camera_offline))){
                return;
            }

            connectView.setBackgroundResource(R.color.transparent);
            connectView.setVisibility(View.GONE);
            connectView.setBackgroundResource(R.color.transparent);
            connectView.setVisibility(View.GONE);
            if (firstTime > 0) {
                deviceMediaSource.enableAudioProduce(audioEnabled);
                deviceMediaRender.enableAudioRender(audioEnabled);
                deviceMediaRenderPiP.enableAudioRender(audioEnabled);
                play(firstTime);
            }
        });
        recordTimeLayout = findViewById(R.id.ll_camera_player_record_time);
        recordTimeText = findViewById(R.id.tv_camera_player_record_time);
        viewContainer = findViewById(R.id.ll_player_bottom);

        findViewById(R.id.back).setOnClickListener(v -> {
            if (isLandscape) {
                switchFullScreen();
            } else {
                finish();
            }
        });
        findViewById(R.id.setting).setOnClickListener(v -> jumpSettings());
        recordTimeLayout.setOnClickListener(v -> {
            String name = "TG-" + System.currentTimeMillis() + ".mp4";
            File file = new File(albumPath, name);
            if (currentPlayer == 0){
                deviceMediaRender.screenRecord().finish(file.getAbsolutePath(), success -> {
                    if (success) {
                        showToast(getString(R.string.record_save));
                    }
                });
            }else{
                deviceMediaRenderPiP.screenRecord().finish(file.getAbsolutePath(), success -> {
                    if (success) {
                        showToast(getString(R.string.record_save));
                    }
                });
            }
        });
        playerContainer.setOnClickListener(v -> switchPlayer(PLAYER_ID_MAIN));
        playerContainerPiP.setOnClickListener(v -> switchPlayer(PLAYER_ID_MINI));
        selectedLayout();
        initDateList();
        showBanner();
        setCameraViewHeight(playerHeight);
        initPlayback();
        mPlayBackFragment.setOnDateItemListener(dateItemListener);
        getSupportFragmentManager().beginTransaction().replace(R.id.camera_view_container, mPlayBackFragment).commitNow();
    }

    private final MessageDateAdapter.OnMessageDateItemListener dateItemListener = new MessageDateAdapter.OnMessageDateItemListener() {
        @Override
        public void onClick(int position, WheelData wheelData) {
            if (selectDayIndex != position){
                list.clear();
                recordTimes.clear();
                mTimePartList.clear();
                deviceMediaSource.enableVideoProduce(false);
                deviceMediaRender.enableVideoRender(false);
                deviceMediaRenderPiP.enableVideoRender(false);
                mPlayBackFragment.setEventList(list, recordTimes, mTimePartList);
                mPlayBackFragment.onPlaybackRecordListResp(false);
            }
            selectDayIndex = position;
            selectDay = wheelData;
            if (deviceFacade.connected()){
                firstTime = 0;
                queryRecord();
            }else{
                TGToast.showToast(R.string.reboot_connect_error);
            }
        }

        @Override
        public void onPlay(int position) {
            DeviceStoragePlayback.Index index = list.get(position);
            play(index);
        }

        @Override
        public void onPlayTime(long time) {
            if (time == 0){
                deviceMediaSource.enableVideoProduce(false);
                deviceMediaRender.enableVideoRender(false);
                deviceMediaRenderPiP.enableVideoRender(false);
                setPlayComplete(ResourcesUtil.getString(R.string.no_video_please_to_scroll), R.color.transparent,false);
            }else{
                play(time);
            }

        }

        @Override
        public void onPlayComplete() {
            TGThreadPool.executeOnUiThread(() -> {
                if (CameraPipPlaybackActivity.this.recordTimes.size() > 0){
                    audioEnabled = deviceMediaSource.isAudioProduceEnabled();
                    stopPlay();
                    setPlayComplete(ResourcesUtil.getString(R.string.message_play_replay), R.drawable.shape_device_list_bg, false);
                }
            });
        }
    };

    private void setPlayComplete(String text, int resId, boolean show){
        connectView.setText(text);
        connectView.setVisibility(View.VISIBLE);
        loadingView.setVisibility(View.GONE);
        connectView.setBackgroundResource(resId);
        playerContainer.setVisibility(show? View.VISIBLE : View.GONE);
        playerContainerPiP.setVisibility(show? View.VISIBLE : View.GONE);
    }

    protected void jumpSettings() {
        if (deviceFacade != null) {
            unregisterICameraListener();
            ActivityHelper.jump2SettingActivityForResult(CameraPipPlaybackActivity.this, mDevice, mOrigin);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mDevice != null && mDevice.isOnline()) {
            if (DeviceHelper.is4GDevice(mDevice) && DeviceHelper.is4GExpired(mDevice, true)) {
                updateServiceState();
            }else{
                deviceMediaSource.enableVideoProduce(true);
                deviceMediaRender.enableVideoRender(true);
                deviceMediaRenderPiP.enableVideoRender(true);

                deviceMediaSource.enableAudioProduce(audioEnabled);
                deviceMediaRender.enableAudioRender(audioEnabled);
                deviceMediaRenderPiP.enableAudioRender(audioEnabled);
            }
            if (mPlayBackFragment != null){
                mPlayBackFragment.setServiceInfo();
            }
        } else {
            playerContainer.setVisibility(View.GONE);
            playerContainerPiP.setVisibility(View.GONE);
            loadingView.setVisibility(View.GONE);
            connectView.setText(R.string.camera_offline);
            connectView.setVisibility(View.VISIBLE);
        }

        deviceFunHelper.setAudioImageResource(audioEnabled? R.drawable.ic_tange_live_soundon : R.drawable.ic_tange_live_soundoff);
    }

    @Override
    protected void updateServiceState() {
        super.updateServiceState();
        if (mDevice.isOnline()){
            if (mPlayBackFragment != null) {
                mPlayBackFragment.setDeviceItem(mDevice);
            }

            if (DeviceHelper.is4GDevice(mDevice) && DeviceHelper.is4GExpired(mDevice, true)) {
                deviceFacade.disconnect();
                playerContainer.setVisibility(View.GONE);
                playerContainerPiP.setVisibility(View.GONE);
                loadingView.setVisibility(View.GONE);

                connectView.setText(R.string.sim_service_expired);
                connectView.setBackgroundResource(R.color.transparent);
                buyButton.setVisibility(View.VISIBLE);

                connectView.setVisibility(View.VISIBLE);

            }else{
                playerContainer.setVisibility(View.VISIBLE);
                playerContainerPiP.setVisibility(View.VISIBLE);
                buyButton.setVisibility(View.GONE);
                connectView.setVisibility(View.GONE);
                deviceMediaSource.enableVideoProduce(true);
                deviceMediaRender.enableVideoRender(true);
                deviceMediaRenderPiP.enableVideoRender(true);

                deviceMediaSource.enableAudioProduce(audioEnabled);
                deviceMediaRender.enableAudioRender(audioEnabled);
                deviceMediaRenderPiP.enableAudioRender(audioEnabled);
                if (!deviceFacade.connected()){
                    deviceFacade.connect();
                    loadingView = findViewById(R.id.loading);
                    loadingView.setVisibility(View.VISIBLE);
                }
            }

            if (mPlayBackFragment != null){
                mPlayBackFragment.setServiceInfo();
            }
        }else{
            playerContainer.setVisibility(View.GONE);
            playerContainerPiP.setVisibility(View.GONE);
            loadingView.setVisibility(View.GONE);
            connectView.setText(R.string.camera_offline);
            connectView.setVisibility(View.VISIBLE);
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isLandscape) {
                switchFullScreen();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void stopPlay(){
        deviceMediaSource.enableAudioProduce(false);
        deviceMediaRender.enableAudioRender(false);
        deviceMediaRenderPiP.enableAudioRender(false);

        deviceMediaSource.enableVideoProduce(false);
        deviceMediaRender.enableVideoRender(false);
        deviceMediaRenderPiP.enableVideoRender(false);
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopPlay();
        screenSaveLocal();
    }

    @Override
    public void receiveIOCtrlData(final int type, final byte[] data) {
        super.receiveIOCtrlData(type, data);
        runOnUiThread(() -> {
            if (type == AVIOCTRLDEFs.TCI_CMD_GET_RUNTIME_STATE_RESP){
                if (mDeviceFeature != null){
                    mDeviceFeature.recordFun = 1;
                    putSettingsInfo();
                }
            }else if (type == AVIOCTRLDEFs.TCI_CMD_GET_MICROPHONE_RESP) {
                byte b = Packet.byteArrayToByte_Little(data, 4);
                deviceSettingsInfo.microphoneOn = b;
                TGLog.d("CameraViewActivity",  "info.b = " + b);
                isMicrophoneClose();
                putSettingsInfo();
            } else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSTREAMCTRL_RESP) {
                deviceSettingsInfo.quality = data[4];
            } else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETRECORD_RESP) {
                deviceSettingsInfo.recordType = Packet.byteArrayToInt_Little(data, 4);
                if (data.length > 8) {
                    deviceSettingsInfo.recordStream = data[8];
                }
                TGLog.d("VideoType", "recordType2 = " + deviceSettingsInfo.recordType);
                putSettingsInfo();
            } else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETSTREAMCTRL_RESP) {
                deviceSettingsInfo.quality = currentResolution;
                putSettingsInfo();
            } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_PRIMARY_VIEW_RESP) {
                int pos = Packet.byteArrayToInt_Little(data, 4);
                mDeviceFeature.currentPlayer = pos;
                deviceSettingsInfo.zoomPos = pos;

                putSettingsInfo();
            } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_LIGHT_RESP){
                CameraHelper.getLightData(data, mDeviceFeature);
                putSettingsInfo();

            } else if (type == AVIOCTRLDEFs.TCI_CMD_SET_COMMAND_RESP) {
                int command = Packet.byteArrayToInt_Little(data, 0);
                int result = Packet.byteArrayToInt_Little(data, 4);

                TGLog.d(ZoomView.TAG, "command" + command + ",result:" + result);
                if (command == AVIOCTRLDEFs.TCI_CMD_GET_RUNTIME_STATE_REQ){
                    if (result == 3 || result == 4){
                        if (mDeviceFeature != null){
                            mDeviceFeature.recordFun = 0;
                            putSettingsInfo();
                        }
                    }
                } else if (command == AVIOCTRLDEFs.TCL_CMD_SET_CAMERA_STATUS_REQ) {
                    TGLog.d("DeviceSettingsActivity", "mDeviceUIHelper.isClickOpenDeviceBtn():" + mDeviceUIHelper.isClickOpenDeviceBtn());
                    if (result == 0 && mDeviceUIHelper.isClickOpenDeviceBtn()) {
                        mDevice.is_open = DeviceStateConstants.DEVICE_OPEN;
                        deviceSettingsInfo.deviceStatus = DeviceStateConstants.DEVICE_OPEN;

                        startLive();

                        putSettingsInfo();
                    }
                    mDeviceUIHelper.setClickOpenDeviceBtn(false);
                }else if (command == AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_GET_FEATURE_RESP) {
                    if (mPlayBackFragment != null) {
                        mPlayBackFragment.setSdCardSize(deviceSettingsInfo.total, true);
                    }
                }
            }
        });
    }


    private void storageInstructionState() {
        new StorageInstruction(deviceFacade).state(sdCardStateResp -> {
            if (sdCardStateResp.getSuccess()){
                sdCardState = sdCardStateResp.getData();
                if (sdCardState != null){
                    deviceSettingsInfo.total = sdCardState.getTotal();
                    if (mPlayBackFragment != null) {
                        mPlayBackFragment.setSdCardSize(deviceSettingsInfo.total, true);
                    }
                    TGThreadPool.executeOnUiThread(() -> {
                        if (sdCardState.getState() == StorageInstruction.State.NOT_EXIST){
                            connectView.setVisibility(View.VISIBLE);
                            connectView.setText(R.string.no_sd_card);
                        }else if (sdCardState.getState() == StorageInstruction.State.ABNORMAL){
                            connectView.setVisibility(View.VISIBLE);
                            connectView.setText("Memory card abnormalities!");
                        }
                    });
                }
            }
        });
    }
    @Override
    public void accept(ConnectStatus connectStatus) {
        Status status = connectStatus.getStatus();

        TGLog.d(TAG, "status:" + status + ",connectStatus:" + connectStatus + ",mDevice:" + mDevice);
        if (status == Status.SUCCESS) {
            if (DeviceHelper.is4GDevice(mDevice) && DeviceHelper.is4GExpired(mDevice, true)) {
                return;
            }
            storageInstructionState();
            queryRecord();
        }else{
            TGLog.d(TAG, "status:" + status);
        }
    }

    private void switchPlayer(int player){
        if (currentPlayer == player) return;
        if (isSaving){
            MsgCenterToast.show(CameraPipPlaybackActivity.this, R.string.camera_player_screencap);
            return;
        }
        currentPlayer = player;
        TGThreadPool.executeOnUiThread(this::selectedLayout);
        showBanner();
        putSettingsInfo();

    }


    @SuppressLint("NotifyDataSetChanged")
    private void initDateList() {
        selectDayIndex = 0;
    }

    @Override
    protected void play(long start){
        connectView.setVisibility(View.GONE);
        playerContainer.setVisibility(View.VISIBLE);
        playerContainerPiP.setVisibility(View.VISIBLE);
        connectView.setVisibility(View.GONE);
        ((DeviceStorageMediaSource)deviceMediaSource).seek(start);
        deviceMediaRender.reset();
        deviceMediaSource.enableVideoProduce(true);
        deviceMediaRender.enableVideoRender(true);
        deviceMediaRenderPiP.enableVideoRender(true);

        TGThreadPool.executeOnUiThreadDelayed(() -> {
            int startTime = mPlayBackFragment.getSecondDay(start);
            mPlayBackFragment.setPlaybackTime(startTime);
            playerContainer.setVisibility(View.VISIBLE);
            playerContainerPiP.setVisibility(View.VISIBLE);
            connectView.setVisibility(View.GONE);
        }, 1000);
    }

    private void queryRecord() {
        if (DeviceHelper.is4GDevice(mDevice) && DeviceHelper.is4GExpired(mDevice, true)) {
            return;
        }
        if (deviceStoragePlayback == null){
            deviceStoragePlayback = new DeviceStoragePlayback(deviceFacade);
        }
        TGLog.d(TAG, "connected:" + deviceFacade.connected());
        String today = DateUtil.getTodayDate();
        if (selectDay != null && !TextUtils.equals(selectDay.date, ResourcesUtil.getString(com.tg.message.R.string.playback_today))) {
            today = selectDay.date;
        }
        deviceStoragePlayback.query(today, listResp -> {
            if (listResp.getSuccess()) {
                list.clear();
                recordTimes.clear();
                mTimePartList.clear();
                List<DeviceStoragePlayback.Index> data = listResp.getData();
                TGLog.d(TAG, "data size:" + data.size());
                for (DeviceStoragePlayback.Index index : data) {
                    TimeRuleView.TimePart timePart = new TimeRuleView.TimePart();
                    timePart.startTime = mPlayBackFragment.getSecondDay(index.getStart());
                    timePart.endTime = mPlayBackFragment.getSecondDay(index.getEnd());
                    timePart.eventType = MessagePlaybackAdapter.getEventName(index.getEvent());
                    TGLog.d(TAG, "timePart.startTime:" + timePart.startTime + ",timePart.endTime:" + timePart.endTime + ",timePart.eventType:" + timePart.eventType);
                    TGLog.d(TAG, "timePart.startTime:" + timePart.startTime + ",timePart.endTime:" + timePart.endTime + ",timePart.eventType:" + timePart.eventType);
                    TGLog.d(TAG, "timePart.startTime:" + DateUtil.formatTimeHHmmss(timePart.startTime) + ",timePart.endTime:" +  DateUtil.formatTimeHHmmss(timePart.endTime) + ",timePart.eventType:" + timePart.eventType);
                    mTimePartList.add(timePart);
                    recordTimes.add(timePart);
                    if (index.getEvent() > 0) {
                        list.add(index);
                    }
                }
                TGThreadPool.executeOnUiThread(() -> {
                    TGLog.d(TAG, "list size:" + list.size());
                    Collections.reverse(list);
                    Collections.reverse(recordTimes);
                    Collections.reverse(mTimePartList);
                    mPlayBackFragment.setEventList(list, recordTimes, mTimePartList);
                    mPlayBackFragment.onPlaybackRecordListResp(false);
                    if (data.size() > 0) {
                        DeviceStoragePlayback.Index index = data.get(data.size() - 1);
                        firstTime = index.getStart();
                        play(index);
                    }else{
                        showNoVideo();
                    }
                });
            }else{
                TGLog.d(TAG, "code:" + listResp.getCode());
                if (DeviceStoragePlayback.ERROR_NO_RECORD == listResp.getCode()){
                    list.clear();
                    TGThreadPool.executeOnUiThread(this::showNoVideo);
                } else if (!deviceFacade.connected()) {
                    TGThreadPool.executeOnUiThread(this::showConnectionFailed);
                }
            }
        });

    }

    private void showConnectionFailed(){
        connectView.setText(R.string.deivce_add_network_error);
        connectView.setVisibility(View.VISIBLE);
        loadingView.setVisibility(View.GONE);
    }

    private void showNoVideo() {
        connectView.setText(R.string.playback_none_sdcard_video);
        connectView.setVisibility(View.VISIBLE);
        deviceMediaSource.enableVideoProduce(false);
        deviceMediaRender.enableVideoRender(false);
        deviceMediaRenderPiP.enableVideoRender(false);
        loadingView.setVisibility(View.GONE);
    }

    void selectedLayout(){
        int pad = DimenUtil.dp2px(this, 2);
        if (currentPlayer == 0) {
            playerContainer.setPadding(pad, pad, pad, pad);
            playerContainer.setBackgroundResource(R.drawable.player_view_pip_vertical_selected);
            playerContainerPiP.setBackgroundColor(Color.TRANSPARENT);
            playerContainerPiP.setPadding(0, 0, 0, 0);
        } else {
            playerContainer.setBackgroundColor(Color.TRANSPARENT);
            playerContainerPiP.setBackgroundResource(R.drawable.player_view_pip_vertical_selected);
            playerContainerPiP.setPadding(pad, pad, pad, pad);
            playerContainer.setPadding(0, 0, 0, 0);
        }
    }
}
